// 上传附件
import { replaceHtml } from '../utils/util';
import { getcellvalue } from '../global/getdata';
import { luckysheetrefreshgrid } from '../global/refresh';
import { rowLocation, colLocation, mouseposition } from '../global/location';
import editor from '../global/editor';
import { modelHTML } from './constant';
import server from './server';
import luckysheetFreezen from './freezen';
import menuButton from './menuButton';
import { getSheetIndex } from '../methods/get';
import locale from '../locale/locale';
import Store from '../store';
import method from '../global/method';
import { getCurrentSheetIndex } from '../global/api';
import dataVerificationCtrl from './dataVerificationCtrl';
import { debounce, isNil } from 'lodash';

const App = 'mkorjl001';
const Space = 'mkorjl';
const User = '7bca079f-c06a-415b-99bc-37a9dd000fb1';
const UrlPath = '/server/deepfos-server'; // 深圳使用'/server/seepln-server'

// 上传文件接口
function uploadAttechmentFile (data) {
    return new Promise((resolve) => {
        $.ajax({
            url: UrlPath + '/platform-file-server/files/upload',
            type: 'post',
            data: data,
            headers: {
                app: App,
                space: Space,
                user: User
            },
            contentType: false, // 必须
            processData: false,
            xhrFields: {
                withCredentials: true    // 前端设置是否带cookie
            },
            crossDomain: true,
            success: function (d) {
                // let sheetList = tableType === 'static' ? await staticSheetTransform(d) : await dynamicSheetTransform(d);
                resolve(d);
            }
        });
    });
}
const attachmentCtrl = {
    item: {
        linkAddress: '',  // 链接地址 网页地址或工作表单元格引用
        linkTooltip: ''  // 提示
    },
    attechment: null,
    createDialog: function () {
        let _this = this;

        const _locale = locale();
        const linkAttechmentText = _locale.linkAttechment;
        const toolbarText = _locale.toolbar;
        const buttonText = _locale.button;

        $("#luckysheet-modal-dialog-mask").show();
        $("#luckysheet-linkAttechment-dialog").remove();
        let content = `<div class="box">
    <div class="box-item">
      <label for="luckysheet-linkAttechment-dialog-linkText">${linkAttechmentText.linkText}：</label>
      <input type="text" id="luckysheet-linkAttechment-dialog-linkText"/>
    </div>
    <div class="box-item">
      <input type="file" id="luckysheet-linkAttechment-uploadfile" className="input" />
    </div>
    <div class="box-item">
      <label for="luckysheet-linkAttechment-dialog-linkTooltip">${linkAttechmentText.linkTooltip}：</label>
      <input type="text" id="luckysheet-linkAttechment-dialog-linkTooltip" placeholder="${linkAttechmentText.placeholder}" />
    </div>`;

        $("body").append(replaceHtml(modelHTML, {
            "id": "luckysheet-linkAttechment-dialog",
            "addclass": "luckysheet-linkAttechment-dialog",
            "title": toolbarText.linkAttechment,
            "content": content,
            "botton": `<button id="luckysheet-linkAttechment-dialog-confirm" class="btn btn-primary">
        ${buttonText.confirm}
      </button>
      <button class="btn btn-default luckysheet-model-close-btn">
        ${buttonText.cancel}
      </button>`,
            "style": "z-index:193"
        }));
        let $t = $("#luckysheet-linkAttechment-dialog").find(".luckysheet-modal-dialog-content").css("min-width", 350).end(),
            myh = $t.outerHeight(),
            myw = $t.outerWidth();
        let winw = $(window).width(),
            winh = $(window).height();
        let scrollLeft = $(document).scrollLeft(),
            scrollTop = $(document).scrollTop();
        $("#luckysheet-linkAttechment-dialog").css({
            "left": (winw + scrollLeft - myw) / 2,
            "top": (winh + scrollTop - myh) / 3
        }).show();

        _this.dataAllocation();
    },
    init: function () {
        let _this = this;

        const _locale = locale();

        // 确认按钮
        $(document).off("click.confirm").on("click.confirm", "#luckysheet-linkAttechment-dialog-confirm", function (e) {
            let last = Store.luckysheet_select_save[Store.luckysheet_select_save.length - 1];
            let rowIndex = last.row_focus || last.row[0];
            let colIndex = last.column_focus || last.column[0];
            var file = $('#luckysheet-linkAttechment-uploadfile').prop('files');

            // 文本
            let linkText = $("#luckysheet-linkAttechment-dialog-linkText").val();

            let linkTooltip = $("#luckysheet-linkAttechment-dialog-linkTooltip").val();
            let item = {
                // linkType: linkType,
                linkAddress: '',
                linkTooltip: linkTooltip
            };

            let historyAttechment = $.extend(true, {}, _this.attechment);
            let currentAttechment = $.extend(true, {}, _this.attechment);
            currentAttechment[rowIndex + "_" + colIndex] = item;

            let d = editor.deepCopyFlowData(Store.flowdata);
            let cell = d[rowIndex][colIndex];

            if (cell == null) {
                cell = {};
            }

            cell.fc = 'rgb(255, 0, 255)';
            cell.un = 1;
            cell.v = cell.m = linkText;

            d[rowIndex][colIndex] = cell;

            _this.ref(
                historyAttechment,
                currentAttechment,
                Store.currentSheetIndex,
                d,
                [{ row: [rowIndex, rowIndex], column: [colIndex, colIndex] }]
            );
            if (file.length) {
                var formData = new FormData();
                formData.append("file", file[0]);
                formData.append("fileType", 'ATT');
                // 上传文件
                uploadAttechmentFile(formData).then((res) => {
                    currentAttechment[rowIndex + "_" + colIndex].linkAddress = res.data;
                    $("#luckysheet-modal-dialog-mask").hide();
                    $("#luckysheet-linkAttechment-dialog").hide();
                });
            }
        });
    },
    dataAllocation: function () {
        let _this = this;

        let last = Store.luckysheet_select_save[Store.luckysheet_select_save.length - 1];
        let rowIndex = last.row_focus || last.row[0];
        let colIndex = last.column_focus || last.column[0];

        let attechment = _this.attechment || {};
        let item = attechment[rowIndex + "_" + colIndex] || {};

        // 文本
        let text = getcellvalue(rowIndex, colIndex, null, 'm');
        $("#luckysheet-linkAttechment-dialog-linkText").val(text);
        // 提示
        let linkTooltip = item.linkTooltip || '';

        $("#luckysheet-linkAttechment-dialog-linkTooltip").val(linkTooltip);
    },
    cellFocus: function (r, c) {
        let _this = this;

        if (_this.attechment == null || _this.attechment[r + '_' + c] == null) {
            return;
        }

        let item = _this.attechment[r + '_' + c];
        var url = `${UrlPath}/platform-file-server/files/download?file=${item.linkAddress.fileName}&id=${item.linkAddress.id}`;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);// get请求，请求地址，是否异步
        xhr.responseType = "blob"; // 返回类型blob
        xhr.setRequestHeader("app", App);
        xhr.setRequestHeader('space', Space);
        xhr.setRequestHeader('user', User);
        // xhr.setRequestHeader('rid', '0d33ea3428302b24f46525cbf932980f-1647498207311-6');

        xhr.onload = function (data, textStatus, request) { // 请求完成处理函数
            if (this.status === 200) {
                var blob = this.response;// 获取返回值
                let downloadElement = document.createElement("a");
                // 创建下载的链接
                let href = window.URL.createObjectURL(blob);
                downloadElement.download = item.linkAddress.fileName;
                downloadElement.href = href;
                // 下载后文件名
                document.body.appendChild(downloadElement);
                // 点击下载
                downloadElement.click();
                // 下载完成移除元素
                document.body.removeChild(downloadElement);
                // 释放掉blob对象
                blob = new Blob([]);
            }
        };
        // 发送ajax请求
        xhr.send();
    },
    overshow: function (event) {
        let _this = this;

        if (event.target && (
            $(event.target).attr('id') === 'luckysheet-hover-overshow' ||
            $(event.target).attr('id') === 'luckysheet-click-overshow' ||
            $(event.target).attr('id') === 'luckysheet-click-overshow-container' ||
            $(event.target).attr('id') === 'luckysheet-hover-overshow-container')) {
            // $('#luckysheet-hover-overshow-container').remove();
            return;
        }
        let isChild = $(event.target).hasClass('attechmentTipContainer');
        $(event.target).parents().each((index, element) => {
            if ($(element).attr('id') === 'luckysheet-hover-overshow' ||
            $(element).attr('id') === 'luckysheet-click-overshow' ||
            $(element).attr('id') === 'luckysheet-click-overshow-container' ||
            $(element).attr('id') === 'luckysheet-hover-overshow-container') isChild = true;
        });
        if (isChild) return;
        if ($(event.target).closest("#luckysheet-cell-main").length == 0) {
            return;
        }
        let mouse = mouseposition(event.pageX, event.pageY);
        let scrollLeft = $("#luckysheet-cell-main").scrollLeft();
        let scrollTop = $("#luckysheet-cell-main").scrollTop();
        let x = mouse[0] + scrollLeft;
        let y = mouse[1] + scrollTop;
        let offsetX = 0;
        let offsetY = 0;
        if (luckysheetFreezen.freezenverticaldata != null && mouse[0] < (luckysheetFreezen.freezenverticaldata[0] - luckysheetFreezen.freezenverticaldata[2])) {
            x = mouse[0] + luckysheetFreezen.freezenverticaldata[2];
            offsetX = scrollLeft;
        }

        if (luckysheetFreezen.freezenhorizontaldata != null && mouse[1] < (luckysheetFreezen.freezenhorizontaldata[0] - luckysheetFreezen.freezenhorizontaldata[2])) {
            y = mouse[1] + luckysheetFreezen.freezenhorizontaldata[2];
            offsetY = scrollTop;
        }

        // if (luckysheetFreezen.freezenverticaldata != null && mouse[0] < (luckysheetFreezen.freezenverticaldata[0] - luckysheetFreezen.freezenverticaldata[2])) {
        //     return;
        // }

        // if (luckysheetFreezen.freezenhorizontaldata != null && mouse[1] < (luckysheetFreezen.freezenhorizontaldata[0] - luckysheetFreezen.freezenhorizontaldata[2])) {
        //     return;
        // }

        let row_index = rowLocation(y)[2];
        let col_index = colLocation(x)[2];
        if (row_index == -1 || col_index == -1) return;
        let margeset = menuButton.mergeborer(Store.flowdata, row_index, col_index);
        if (!!margeset) {
            row_index = margeset.row[2];
            col_index = margeset.column[2];
        }
        const overshowData = $("#luckysheet-hover-overshow").data();
        if (overshowData && overshowData.rc === `${row_index}-${col_index}`) return;
        $("#luckysheet-hover-overshow-container").remove();
        const file = Store.luckysheetfile[getCurrentSheetIndex()];
        const dataVerification = file.dataVerification || {};
        let verifyItem = dataVerification[`${row_index}_${col_index}`];
        let cellData = {};
        if (Store.flowdata[row_index] && Store.flowdata[row_index][col_index]) {
            cellData = Store.flowdata[row_index][col_index];
        }
        let isFile = false;

        let row = Store.visibledatarow[row_index],
            row_pre = row_index - 1 == -1 ? 0 : Store.visibledatarow[row_index - 1];
        let col = Store.visibledatacolumn[col_index],
            col_pre = col_index - 1 == -1 ? 0 : Store.visibledatacolumn[col_index - 1];

        if (!!margeset) {
            row = margeset.row[1];
            row_pre = margeset.row[0];

            col = margeset.column[1];
            col_pre = margeset.column[0];
        }
        col_pre += offsetX;
        row_pre += offsetY;
        row += offsetY;
        col += offsetX;
        this.show(verifyItem, cellData, isFile, row, col, row_pre, col_pre, row_index, col_index);
    },

    show: debounce(function (verifyItem, cellData, isFile, row, col, row_pre, col_pre, row_index, col_index) {
        // if ((cellData.tag && ((cellData.tag.file && cellData.tag.file.length > 0) || cellData.tag.psInfo || cellData.tag.hintErrorText))) isFile = true;
        // if (!isFile) {
        //     return;
        // }
        let hintText = '';
        let hintError = '';
        if (verifyItem) {
            if (verifyItem.hintShow) {
                hintText = dataVerificationCtrl.getHintText(verifyItem) || '';
            }
            let validateValue =  isNil(cellData.v) ? '' : cellData.v;
            if (cellData.ct && cellData.ct.t == 'd') {
                validateValue = cellData.m || '';
            }
            if (verifyItem != null && !isNil(cellData.m) && cellData.m !== '' && !dataVerificationCtrl.validateCellData(validateValue.toString(), verifyItem)) {
                hintError = dataVerificationCtrl.getFailureText(verifyItem) || '';
            }
        }
        let scrollTop = $("#luckysheet-cell-main").scrollTop();
        let html = `<div class="attechmentTipContainer" id="luckysheet-hover-overshow-container" style="display:none;position:absolute;left:${col_pre}px;top:${row}px;z-index:199;"><div id="luckysheet-hover-overshow" data-rc="${row_index}-${col_index}" class="attechmentTip" style="background:#fff;z-index:200;"></div></div>`;

        $(html).appendTo($("#luckysheet-cell-main"));
        $('#luckysheet-hover-overshow').mousedown(function (event) {
            event.stopPropagation();
        });
        let msg = {};
        if (Store.flowdata[row_index][col_index]) {
            if (Store.flowdata[row_index][col_index].msg) {
                msg = {
                    ...Store.flowdata[row_index][col_index].msg
                };
            }
        }
        if (hintText || hintError) {
            msg = {
                ...msg,
                validateError: hintError,
                validateHint: hintText
            };
        }
        method.createHookFunction("mouseOverAttechment", {
            ...Store.flowdata[row_index][col_index],
            msg
        },
        `luckysheet-hover-overshow-container`,
        {
            "r": row_index,
            "c": col_index
        }
        );
        Store.overShowPos = {
            row: row_index,
            col: col_index
        };
        if (Store.cellmainHeight + scrollTop - row - 20 < $('#luckysheet-hover-overshow').height()) {
            $('#luckysheet-hover-overshow-container').css('top', `${row_pre - $('#luckysheet-hover-overshow').height() - 30}px`);
        }
    }, 200),

    ref: function (historyAttechment, currentAttechment, sheetIndex, d, range) {
        let _this = this;

        if (Store.clearjfundo) {
            Store.jfundo.length = 0;

            let redo = {};
            redo.type = "updateHyperAttechment";
            redo.sheetIndex = sheetIndex;
            redo.historyAttechment = historyAttechment;
            redo.currentAttechment = currentAttechment;
            redo.data = Store.flowdata;
            redo.curData = d;
            redo.range = range;
            Store.jfredo.push(redo);
        }
        _this.attechment = currentAttechment;
        Store.luckysheetfile[getSheetIndex(sheetIndex)].attechment = currentAttechment;
        Store.flowdata = d;
        editor.webWorkerFlowDataCache(Store.flowdata);// worker存数据
        Store.luckysheetfile[getSheetIndex(sheetIndex)].data = Store.flowdata;

        // 共享编辑模式
        if (server.allowUpdate) {
            server.saveParam("all", sheetIndex, currentAttechment, { "k": "attechment" });
            server.historyParam(Store.flowdata, sheetIndex, range[0]);
        }

        setTimeout(function () {
            luckysheetrefreshgrid();
        }, 1);
    },
    // 删除附件
    delCell: function () {
        let _this = this;
        let last = Store.luckysheet_select_save[Store.luckysheet_select_save.length - 1];
        let rowIndex = last.row_focus || last.row[0];
        let colIndex = last.column_focus || last.column[0];

        let historyAttechment = $.extend(true, {}, _this.attechment);
        let currentAttechment = $.extend(true, {}, _this.attechment);
        if (currentAttechment[rowIndex + "_" + colIndex]) {
            delete currentAttechment[rowIndex + "_" + colIndex];
        } else {
            return;
        }

        let d = editor.deepCopyFlowData(Store.flowdata);
        let cell = d[rowIndex][colIndex];

        if (cell == null) {
            cell = {};
        }

        cell.fc = 'rgb(0, 0, 0)';
        cell.un = 0;

        d[rowIndex][colIndex] = cell;

        _this.ref(
            historyAttechment,
            currentAttechment,
            Store.currentSheetIndex,
            d,
            [{ row: [rowIndex, rowIndex], column: [colIndex, colIndex] }]
        );
    }
};

export default attachmentCtrl;
